﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Xml;
using System.Windows.Forms;

using PriErp.Commands;
using PriErp.Dal;
using PriErp.Tools.Extensions;
using DevComponents.DotNetBar.SuperGrid;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;

namespace PriErp.Frm
{
    public partial class UsersCtl : UserControl,IView
    {
        #region constructor
        public UsersCtl()
        {
            InitializeComponent();
            InitializeGrid();
        }
        #endregion

        #region Properties
        /// <summary>
        /// 排序字段
        /// </summary>
        protected string sortField = "userid";
        /// <summary>
        /// 排序方式
        /// </summary>
        protected SortDirection sortType = SortDirection.Ascending;
        /// <summary>
        /// 操作等待显示
        /// </summary>
        protected OpaqueLayerCtl _opaqueLayer;
        #endregion

        #region IView Methods
        /// <summary>
        /// 当前视图名称
        /// </summary>
        public virtual ViewNames CurrentView
        {
            get { return ViewNames.Users; }
        }

        /// <summary>
        /// 载入数据
        /// </summary>
        /// <param name="bFirst"></param>
        public virtual void LoadData()
        {
            this.UIThread(delegate
            {
                ShowWaitingInfo("正在载入数据，请稍后...");
                RefreshData(true);
                RemoveOpaqueLayer(false);
            });
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        /// <param name="bFirst"></param>
        public virtual void RefreshData(bool bFirst)
        {
            if (bFirst)
                gridPager_Main.RecordCount = GetRecordCount();
            string sortExp = string.Format("{0} {1}", sortField, sortType == SortDirection.Descending ? "desc" : "asc");
            DataGrid_Main.PrimaryGrid.DataSource = GetDataSource(sortExp);
        }
        #endregion

        #region Command Methods
        /// <summary>
        /// 构建表格
        /// </summary>
        protected virtual void InitializeGrid()
        {
            String xmlPath = AppSetting.GridPath;
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlPath);
            string xpath = string.Format("//View/Group[@name='{0}']/Column", CurrentView);
            XmlNodeList ColumnList = doc.SelectNodes(xpath);
            ReginsCommand.InitGridColumns(DataGrid_Main, ColumnList, true, false);
        }

        /// <summary>
        /// 获取项目数
        /// </summary>
        /// <returns></returns>
        protected virtual int GetRecordCount()
        {
            return UserDAL.GetUsersCount();
        }

        /// <summary>
        /// 获取数据源
        /// </summary>
        /// <param name="sortExp"></param>
        /// <returns></returns>
        protected virtual DataTable GetDataSource(string sortExp)
        {
            return UserDAL.GetUsers(gridPager_Main.CurrentPageIndex, gridPager_Main.PageSize, sortExp);
        }

        /// <summary>
        /// 获取选择行的ID信息
        /// </summary>
        /// <returns></returns>
        protected virtual List<int> GetSelectID()
        {
            List<int> ids = new List<int>();

            GridPanel pal = DataGrid_Main.PrimaryGrid;
            int iCount = pal.Rows.Count;
            for (int i = 0; i < iCount; i++)
            {
                GridCell cell = DataGrid_Main.GetCell(i, 0);
                if (cell.Value.ToStringEmpty().ToBoolean())
                {
                    ids.Add(DataGrid_Main.GetCell(i, 1).Value.ToStringEmpty().ToInt32());
                }
            }
            ids.Remove(GlobalProvider.UserInfo.UserID);//无法对自己进行权限和删除操作
            ids.Remove(1);//超级管理员禁止操作
            return ids;
        }

        /// <summary>
        /// 显示等待提示
        /// </summary>
        /// <param name="message">提示信息</param>
        protected virtual void ShowWaitingInfo(string message)
        {
            WaitingCtl wait = new WaitingCtl();
            wait.Anchor = AnchorStyles.None;
            wait.Message = message;
            if (_opaqueLayer == null)
                _opaqueLayer = new OpaqueLayerCtl();
            this.ShowOpaqueLayer(wait, _opaqueLayer);
        }

        /// <summary>
        /// 移除遮盖层
        /// </summary>
        /// <param name="refresh">是否刷新数据</param>
        protected virtual void RemoveOpaqueLayer(bool refresh)
        {
            if (refresh)
            {
                RefreshData(true);
            }
            this.RemoveControl(_opaqueLayer);
        }
        /// <summary>
        /// 移除遮盖层(刷新数据) 
        /// </summary>
        protected virtual void RemoveOpaqueLayerRefreshData()
        {
            RemoveOpaqueLayer(true);
        }
        /// <summary>
        /// 移除遮盖层(默认不刷新) 
        /// </summary>
        protected virtual void RemoveOpaqueLayer()
        {
            RemoveOpaqueLayer(false);
        }
        #endregion

        #region SuperGrid Events
        /// <summary>
        /// 自定义格式化列
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void Grid_Main_GetCellFormattedValue(object sender, GridGetCellFormattedValueEventArgs e)
        {
            int columnIndex = e.GridCell.ColumnIndex;
            if (columnIndex == 3)
            {
                if (GlobalProvider.UserInfo.Master != PowerType.Admin && e.GridCell.GridRow.GetCell(1).Value.ToString().ToInt32() != GlobalProvider.UserInfo.UserID)
                {
                    e.FormattedValue = "********";
                }
               // e.GridCell.InfoText = "查看详情";
                //e.FormattedValue = (gridPager_Main.CurrentPageIndex - 1) * gridPager_Main.PageSize + e.GridCell.GridRow.FullIndex + 1;
            }
            else if (columnIndex == 6)
            {
                e.FormattedValue = ((UserStatus)e.GridCell.Value.ToString().ToInt32()).GetDescription();
            }
            else if (columnIndex == 7)
            {
                e.FormattedValue = ((PowerType)e.GridCell.Value.ToString().ToInt32()).GetDescription();
            }
        }

        /// <summary>
        /// 禁用自带的排序功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void Grid_Main_RowsSorting(object sender, GridCancelEventArgs e)
        {
            e.Cancel = true;
        }

        /// <summary>
        /// This routine is called when the user attempts to edit
        /// a given cell. We are using this as an illustration of one way
        /// to prevent edits while yet keeping all other behavior and
        /// functionality the same. Edits could be canceled for any
        /// programmatic reason through this mechanism.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void DataGrid_Main_BeginEdit(object sender, GridEditEventArgs e)
        {
            if (e.GridCell.ColumnIndex > 0)
                e.Cancel = true;
        }

        /// <summary>
        /// 右键菜单实现
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void Grid_Main_CellMouseUp(object sender, GridCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (DataGrid_Main.ActiveRow == null) return;
                int userID = DataGrid_Main.GetCell(DataGrid_Main.ActiveRow.GridIndex, 1).Value.ToStringEmpty().ToInt32();
                bool bEnable = GlobalProvider.UserInfo.Master == PowerType.Admin || userID == GlobalProvider.UserInfo.UserID;
                btnEditInfo.Enabled = bEnable;
                btnDelete.Enabled = bForbiddenUsers.Enabled = bActiveUsers.Enabled = GlobalProvider.UserInfo.Master == PowerType.Admin;
                bActionMenu.Popup(Control.MousePosition);
            }
        }

        /// <summary>
        /// 自定义的排序及选择菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void Grid_Main_ColumnHeaderClick(object sender, GridColumnHeaderClickEventArgs e)
        {
            GridColumn col = e.GridColumn;
            if(col.ColumnIndex==0)
            {
                bSelectMenu.Popup(Control.MousePosition);
            }
            else if (col.ColumnSortMode == ColumnSortMode.Single)
            {
                if (sortType == SortDirection.Descending)
                    sortType = col.SortDirection = SortDirection.Ascending;
                else
                    sortType = col.SortDirection = SortDirection.Descending;
                sortField = col.DataPropertyName;
                RefreshData(false);
            }
        }
        #endregion 

        #region Selected Events
        /// <summary>
        /// 全选、全不选、反选
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void SelectCommand_Executed(object sender, EventArgs e)
        {
            ICommandSource source = sender as ICommandSource;
            string parm = source.CommandParameter.ToString();
            bool result = parm == "Null" ? false : true;

            GridPanel pal = DataGrid_Main.PrimaryGrid;
            int iCount = pal.Rows.Count;
            for (int i = 0; i < iCount; i++)
            {
                GridCell cell = DataGrid_Main.GetCell(i, 0);
                if (parm == "Reverse")
                {
                    cell.Value = cell.Value.ToStringEmpty().ToBoolean() ^ result;
                }
                else
                    cell.Value = result;
            }
        }
        #endregion

        #region Pageing Events
        /// <summary>
        /// 翻页事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UserOnPageChanging(object sender, EventArgs e)
        {
            RefreshData(false);
        }
        #endregion

        #region Right MouseButton PopMenu Events
        //权限未做太多控制，初期简单化
        /// <summary>
        /// 编辑用户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void btnEditInfo_Click(object sender, EventArgs e)
        {
            if (DataGrid_Main.ActiveRow == null)
                return;
            int userID = DataGrid_Main.GetCell(DataGrid_Main.ActiveRow.GridIndex, 1).Value.ToStringEmpty().ToInt32();
            if (GlobalProvider.UserInfo.Master == PowerType.Admin || userID == GlobalProvider.UserInfo.UserID)
            {
                UserDlg dlg = new UserDlg();
                //载入信息
                dlg.OnSubmit += new MethodInvoker(RemoveOpaqueLayerRefreshData);
                dlg.OnCancel += new MethodInvoker(RemoveOpaqueLayer);
                this.ShowOpaqueLayer(dlg, _opaqueLayer);
            }
            else
                MsgBoxEx.Show(this,"非管理员账号无权操作其他账号!\r\n请联系超级管理员!", "错误提示", MessageBoxIcon.Error);
        }
        /// <summary>
        /// 删除所选用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void btnDelete_Click(object sender, EventArgs e)
        {
            if (GlobalProvider.UserInfo.Master == PowerType.Admin)
            {
                bool brefresh = false;
                Action ThreadWorkingHandle = delegate()
                {
                    List<int> ids = GetSelectID();
                    ShowWaitingInfo("正在执行【删除选定用户】操作，请稍后......");
                    brefresh=UserDAL.Delete(ids);
                    System.Threading.Thread.Sleep(500);
                };
                Action ThreadCompletedHandle = delegate()
                {
                    RemoveOpaqueLayer(brefresh);
                };
                PriErpCommand.RunBackground(ThreadWorkingHandle, ThreadCompletedHandle);
            }
            else
            {
                MsgBoxEx.Show(this, "您没有权限操作!\r\n请联系超级管理员!", "警告", MessageBoxIcon.Warning);
            }
        }

        /// <summary>
        /// 禁用所选用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void bForbiddenUsers_Click(object sender, EventArgs e)
        {
            if (GlobalProvider.UserInfo.Master == PowerType.Admin)
            {
                bool brefresh = false;
                Action ThreadWorkingHandle = delegate()
                {
                    List<int> ids = GetSelectID();
                    ShowWaitingInfo("正在执行【禁用选定用户】操作，请稍后......");
                    brefresh = UserDAL.Forbidden(ids);
                    System.Threading.Thread.Sleep(500);
                };
                Action ThreadCompletedHandle = delegate()
                {
                    RemoveOpaqueLayer(brefresh);
                };
                PriErpCommand.RunBackground(ThreadWorkingHandle, ThreadCompletedHandle);
            }
            else
            {
                MsgBoxEx.Show(this, "您没有权限操作!\r\n请联系超级管理员!", "警告", MessageBoxIcon.Warning);
            }
        }
        /// <summary>
        /// 激活所选用户
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected virtual void bActiveUsers_Click(object sender, EventArgs e)
        {
            if (GlobalProvider.UserInfo.Master == PowerType.Admin)
            {
                bool brefresh = false;
                Action ThreadWorkingHandle = delegate()
                {
                    List<int> ids = GetSelectID();
                    ShowWaitingInfo("正在执行【禁用选定用户】操作，请稍后......");
                    brefresh = UserDAL.Active(ids);
                    System.Threading.Thread.Sleep(500);
                };
                Action ThreadCompletedHandle = delegate()
                {
                    RemoveOpaqueLayer(brefresh);
                };
                PriErpCommand.RunBackground(ThreadWorkingHandle, ThreadCompletedHandle);
            }
            else
            {
                MsgBoxEx.Show(this, "您没有权限操作!\r\n请联系超级管理员!", "警告", MessageBoxIcon.Warning);
            }
        }
        #endregion

       
    }
}
